package datenverwaltung;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;

import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

import com.main.meldungsverwaltung.GUI;

/**
 * Lädt alle aktiven Meldungen herunter und speichert sie in der MeldungsListe.
 * 
 * @author Felix
 * 
 */
public class MeldungsDownload extends Thread implements DBVerbindung {

	public static ArrayList<Meldung> meldungsListe = new ArrayList<Meldung>();
	private TableModel model;
	private JTable table;
	private Connection connection;

	public MeldungsDownload(JTable table) {
		this.table = table;
		createTableModel();
		try {
			connection = getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			meldungsListe = getMeldungen();
			createTableModel();
			table.setModel(model);
		} catch (Exception e) {
			e.printStackTrace();
		}
		while (GUI.running) {
			int tableWidth = table.getWidth();
			table.getColumnModel().getColumn(0)
					.setPreferredWidth((int) (tableWidth * 0.07));
			table.getColumnModel().getColumn(1)
					.setPreferredWidth((int) (tableWidth * 0.1));
			table.getColumnModel().getColumn(2)
					.setPreferredWidth((int) (tableWidth * 0.4));
			table.getColumnModel().getColumn(3)
					.setPreferredWidth((int) (tableWidth * 0.1));
			table.getColumnModel().getColumn(4)
					.setPreferredWidth((int) (tableWidth * 0.33));
			try {
				meldungsListe = getMeldungen();
				table.setModel(model);
				table.repaint();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				sleep(4000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public Connection getConnection() throws Exception {
		Connection connection;
		Class.forName("com.mysql.jdbc.Driver");
		connection = DriverManager.getConnection(DB_CONNECTION_URL,
				DB_USERNAME, DB_PASSWORD);
		return connection;
	}

	@Override
	public ResultSet executeStatementOnDB(String select) throws Exception {
		Statement statement = connection.createStatement();
		ResultSet result = statement.executeQuery(select);
		return result;
	}

	/**
	 * Liefert eine Liste der Meldungen zurück.
	 * 
	 * @return ArrayList von Meldungen
	 * @throws Exception
	 */
	public ArrayList<Meldung> getMeldungen() throws Exception {
		ArrayList<Meldung> liste = new ArrayList<Meldung>();
		String select = "select tracker.id tracker_id,art,ort,erstellzeitpunkt,latitude,longitude,beschreibung,anzAktiv,anzInaktiv,meldung.id from tracker,meldung where tracker.id=meldung.tracker_id and meldung.aktiv=true order by erstellzeitpunkt desc;";
		ResultSet result = executeStatementOnDB(select);
		while (result.next()) {
			String zeitString = result.getString("erstellzeitpunkt");
			Timestamp datetime = Timestamp.valueOf(zeitString);
			GPSKoordinaten koordinaten = new GPSKoordinaten(
					Double.parseDouble(result.getString("latitude")),
					Double.parseDouble(result.getString("longitude")));
			Meldung m = new Meldung(result.getString("art"),
					result.getString("ort"), result.getString("tracker_id"),
					result.getString("id"), result.getString("beschreibung"),
					datetime, koordinaten, Integer.parseInt(result
							.getString("anzAktiv")), Integer.parseInt(result
							.getString("anzInaktiv")));
			liste.add(m);
		}
		return liste;
	}

	/**
	 * Erstellt das TableModel für die Tabelle.
	 */
	private void createTableModel() {
		model = new TableModel() {

			@Override
			public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
			}

			@Override
			public void removeTableModelListener(TableModelListener l) {
				// TODO Auto-generated method stub

			}

			@Override
			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return false;
			}

			@Override
			public Object getValueAt(int rowIndex, int columnIndex) {
				return meldungsListe.get(rowIndex).get(columnIndex);
			}

			@Override
			public int getRowCount() {
				return meldungsListe.size();
			}

			@Override
			public String getColumnName(int columnIndex) {
				switch (columnIndex) {
				case 0:
					return "ID";
				case 1:
					return "Art";
				case 2:
					return "Ort";
				case 3:
					return "Trucker-ID";
				case 4:
					return "Erstellzeit";
				default:
					return "";
				}
			}

			@Override
			public int getColumnCount() {
				return 5;
			}

			@Override
			public Class<?> getColumnClass(int columnIndex) {
				return String.class;
			}

			@Override
			public void addTableModelListener(TableModelListener l) {
				// TODO Auto-generated method stub

			}
		};
	}

	public TableModel getModel() {
		return model;
	}

}
